import os
import sys

try:
    migration_file_path = r'f:\和臻OA\backend\WxApi\migrations\0005_crmappraisalproject_crmbidding_crmbiddingproject_and_more.py'
    new_migration_file_path_0006 = r'f:\和臻OA\backend\WxApi\migrations\0006_update_user_dept.py'

    if not os.path.exists(migration_file_path):
        print(f"File not found: {migration_file_path}")
        sys.exit(1)

    with open(migration_file_path, 'r', encoding='utf-8') as f:
        content = f.read()

    lines = content.split('\n')
    print(f"Total lines: {len(lines)}")

    # Hardcoded split point based on file inspection (line 2322, index 2321)
    split_line_index = 2321
    
    if split_line_index >= len(lines):
        print(f"Index {split_line_index} out of range")
        sys.exit(1)

    print(f"Line {split_line_index+1}: {lines[split_line_index]}")

    # Verification
    if 'migrations.RenameField' not in lines[split_line_index]:
        print(f"Warning: Line {split_line_index+1} is not RenameField")
        found = False
        for i in range(0, len(lines)):
            if 'migrations.RenameField' in lines[i]:
                # check next line for user
                if i+1 < len(lines) and 'model_name="user"' in lines[i+1]:
                    split_line_index = i
                    print(f"Found it at {i+1}")
                    found = True
                    break
        if not found:
            print("Could not find RenameField operation")
            sys.exit(1)

    print(f"Split point found at line {split_line_index + 1}")

    # Construct 0005 content
    content_0005_lines = lines[:split_line_index]
    # Ensure we close the class and operations list
    # The last line of content_0005_lines is the comma after the previous op.
    # We assume the file structure is correct.
    content_0005 = '\n'.join(content_0005_lines) + '\n    ]\n'

    # Construct 0006 content
    content_0006_header = """# Generated by split_migration.py

import django.db.models.deletion
from django.db import migrations, models


class Migration(migrations.Migration):

    dependencies = [
        ("WxApi", "0005_crmappraisalproject_crmbidding_crmbiddingproject_and_more"),
    ]

    operations = [
        migrations.RunSQL(
            "DROP TABLE IF EXISTS sys_user_role; DROP TABLE IF EXISTS sys_user_post; DROP TABLE IF EXISTS sys_role_dept; DROP TABLE IF EXISTS sys_role_menu; DROP TABLE IF EXISTS sys_user; DROP TABLE IF EXISTS sys_dept;"
        ),
"""

    content_0006_body_lines = lines[split_line_index:]
    content_0006_body = '\n'.join(content_0006_body_lines)

    content_0006 = content_0006_header + content_0006_body

    # Write files
    with open(migration_file_path, 'w', encoding='utf-8') as f:
        f.write(content_0005)

    with open(new_migration_file_path_0006, 'w', encoding='utf-8') as f:
        f.write(content_0006)

    print("Successfully split migration files.")

except Exception as e:
    print(f"An error occurred: {e}")
    import traceback
    traceback.print_exc()
    sys.exit(1)
